package dian.qing.li.demo.security.config.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 缓存请求数据
 *
 * @Author: liqingdian
 */
@Slf4j
public class WrapperRequest extends HttpServletRequestWrapper {

    private byte[] requestBody;// 用于将流保存下来
    private InputStream is;

    public WrapperRequest(HttpServletRequest request) throws IOException {
        super(request);
        is = request.getInputStream();
        String sessionStream = StreamUtils.copyToString(is, StandardCharsets.UTF_8);
        requestBody = sessionStream.getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody);

        return new ServletInputStream() {

            @Override
            public int read() throws IOException {
                return bais.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }

    public byte[] getRequestBody() {
        return requestBody;
    }
}
